TQWEET = {

    appendTo: '#tqtwitter',

    loadTweets: function () {

        $.when(
		$.ajax({
		    url: 'http://search.twitter.com/search.json',
		    type: 'GET',
		    async: false,
		    dataType: 'jsonp',
		    data: {
		        q: TQWEET_GLOBAL.query,
		        rpp: TQWEET_GLOBAL.maxTweets
		    },
		    success: function (data, textStatus, xhr) {

		        var html = '<div class="tweet"><div><a href="https://twitter.com/intent/user?screen_name=USER" target="_blank"><img id="avatar" src="IMG_SRC" title="FULL_NAME"/></a><a href="http://twitter.com/intent/user?screen_name=USER" target="_blank"><strong>FULL_NAME</strong></a><span class="user">@USER</span><span class="time">TIME_AGO</span><br>TEXT_TWEET</div>';

		        $(TQWEET.appendTo).children().remove();
		        // append tweets into page
		        for (var i = 0; i < data.results.length; i++) {

		            $(TQWEET.appendTo).append(html.replace('TEXT_TWEET', TWEET.ify.clean(data.results[i].text))
							   .replace(/USER/g, data.results[i].from_user)
							   .replace('TIME_AGO', TQWEET.timeAgo(data.results[i].created_at))
							   .replace('IMG_SRC', data.results[i].profile_image_url)
							   .replace(/FULL_NAME/g, data.results[i].from_user_name)
							   );
		        }

		    }

		})
		 ).then(function (ajaxArgs) {

		     CreatePager();
		     $('#tqtwitter').css({ 'opacity': '1', 'filter': 'alpha(opacity=100)' });
		     $('.imgLoader').hide();
		     $('.refreshButton').text('refresh');
		 });
        //return result;	
    },

    /**
    * @param {string} twitter date string returned from Twitter API
    * @return {string} relative time like "2H" as 2 hours ago
    */
    timeAgo: function (dateString) {
        var rightNow = new Date();
        var created = new Date(dateString);

        if ($.browser.msie) {
            // IE can't parse Ruby dates
            created = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
        }

        var diff = rightNow - created;

        var second = 1000,
            minute = second * 60,
            hour = minute * 60,
            day = hour * 24;

        if (isNaN(diff) || diff < 0) {return ""; }
        if (diff < second * 2) {return "right now";}
        if (diff < minute) {return Math.floor(diff / second) + "S";}
        if (diff < hour) {return Math.floor(diff / minute) + "M";}
        if (diff < day) {return Math.floor(diff / hour) + "H";}
        if (diff < day * 365) {return Math.floor(diff / day) + "D";}
        else {return "1Y";}
    }// timeAgo()
};

var count=0;
$(document).ready(function () {
    TQWEET.loadTweets();
});


//refresh button
function Refresh(){
$('#tqtwitter').css({'opacity' : '0.4', 'filter' : 'alpha(opacity=40)'});
$('.imgLoader').show();
$('.refreshButton').text('loading');
  TQWEET.loadTweets();}
